<template>
    <van-field
        :required="required"
        center
        :name="uploadField"
        :label="label"
        :placeholder="`请上传${label}`"
        :rules="[{ required: required, message: '请上传' + label }]"
    >
        <template #input>
            <van-uploader
                v-model="modelArr"
                :readonly="readonly"
                :deletable="!readonly"
                :max-count="maxCount"
                :upload-text="uploadText"
                :before-delete="beforeDelete(uploadField)"
                :before-read="beforeRead"
                :after-read="afterRead(uploadField)"
            />
        </template>
    </van-field>
</template>

<script lang="ts" setup>
    import { markRaw, reactive, ref, toRaw, onMounted, watchEffect } from 'vue';
    import type { Ref } from 'vue';
    import { showDialog, showLoadingToast, closeToast, showFailToast } from 'vant';
    import { fileUploadBase64ExApi, idOrcApi } from '@/apis';
    import { compressImg, isCardID } from '@/utils';
    import Compressor from 'compressorjs';

    const {
        readonly = false,
        required = false,
        label = '',
        maxCount,
        uploadText = '',
        uploadField = '',
        modelValue = '',
        allFormData = {},
        modifyFormData = {},
    } = defineProps<{
        readonly?: boolean;
        required?: boolean;
        label?: string;
        maxCount?: number;
        uploadText?: string;
        uploadField?: string;
        modelValue?: string;
        allFormData?: any; //整个对象，在上传身份证的时候可以用，这样就不用传很多参数去改
        modifyFormData?: any; //修改参数对象，例{sh_ex36: '姓名'}
    }>();
    const emits = defineEmits<{
        // (e: 'update:modelValue', data: any): void;
        'update:modelValue': [data: any];
        'update:allFormData': [data: any];
        'update:modifyFormData': [data: any];
    }>();
    const modelArr: Ref<any[]> = ref([]);
    watchEffect(() => {
        modelArr.value = [];
        if (modelValue) {
            console.log(modelValue);
            modelValue.split(',').forEach((item, index) => {
                modelArr.value.push({
                    url: item,
                    isImage: true,
                });
            });
        }
    });
    const beforeDelete = (data) => {
        return (file, detail) => {
            let myarr1 = modelValue.split(',');
            myarr1.splice(detail.index, 1);
            emits('update:modelValue', myarr1.join(','));
            return true;
        };
    };
    const beforeRead: any = (file) => {
        console.log(file);
        return new Promise((resolve, reject) => {
            if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
                showFailToast('请上传 jpg/png 格式图片');
                reject('请上传 jpg/png 格式图片');
            } else if (file.size / 1024 / 1024 > 2) {
                new Compressor(file, {
                    quality: 0.6,
                    success(result) {
                        console.log(result);
                        // 压缩成功后的处理
                        const compressedFile = new File([result], file.name, { type: result.type });
                        // 可以在这里预览、上传或者做其他处理
                        console.log('Compressed file:', compressedFile);
                        // 如果需要上传，可以在这里执行上传操作
                        resolve(compressedFile);
                    },
                    error(err) {
                        reject('压缩失败');
                        // console.log("Compressor error:", err.message);
                    },
                });
            } else {
                resolve(file);
            }
        });
    };
    const afterRead = (imgField, isIdOrc = false) => {
        return (file) => {
            file.status = 'uploading';
            file.message = '上传中...';
            // 执行压缩图片并上传
            // let obj = new compressImg(file, afterRead2, imgField, isIdOrc, file);
            return (file) => {
                file.status = 'uploading';
                file.message = '上传中...';
                console.log(file);
                // 执行压缩图片并上传
                // let obj = new compressImg(file, afterRead2, imgField, isIdOrc, file);
                fileUploadBase64ExApi({
                    data: file.content,
                    sCode: 'kmxbyg',
                })
                    .then((res) => {
                        // file.status = 'done';
                        // file.message = '上传完成';
                        console.log(res);
                        if (Object.keys(modifyFormData).length > 0) {
                            // 拍照识按钮要显示不能设置maxCount=1，不然上传一张图就没了按钮
                            if (modelArr.value.length > 1) {
                                modelArr.value.shift();
                            }
                            emits('update:modelValue', res[0].url);
                            // 用过拍照识别后续上传身份证都要进行idOrc验证信息
                            idOrcApi({
                                img: file.content,
                            })
                                .then((res: any) => {
                                    if (res.idcard_number_type == 1) {
                                        let obj = res.words_result;

                                        let myobj1 = JSON.parse(JSON.stringify(allFormData));
                                        Object.keys(modifyFormData).forEach((item) => {
                                            myobj1[item] = obj[modifyFormData[item]].words;
                                        });
                                        emits('update:allFormData', myobj1);
                                    } else {
                                        throw new Error('身份证验证失败');
                                    }
                                    file.status = 'done';
                                    file.message = '上传完成';
                                })
                                .catch((err) => {
                                    console.log(err);
                                    showFailToast('识别失败');
                                    file.status = 'done';
                                    file.message = '上传完成';
                                });
                        } else {
                            if (modelValue) {
                                emits('update:modelValue', modelValue.concat(',', res[0].url));
                            } else {
                                emits('update:modelValue', modelValue.concat(res[0].url));
                            }
                            file.status = 'done';
                            file.message = '上传完成';
                        }
                    })
                    .catch((err) => {
                        file.status = 'failed';
                        file.message = '上传失败';
                        modelArr.value.pop();
                        showFailToast('上传失败');
                        console.log(err);
                    });
            };
        };
    };
    // 组件方法 获取 流
    const afterRead2 = (imgField, isIdOrc, file, obj) => {
        // failed done
        // file.status = 'uploading';
        // file.message = '上传中...';
        // file.file: 文件 file.content: base64图片
        console.log(file);
        // let f = new FormData()
        // f.append('file', file.file)

        fileUploadBase64ExApi({
            data: obj,
            sCode: 'kmxbyg',
        })
            .then((res) => {
                // file.status = 'done';
                // file.message = '上传完成';
                console.log(res);

                if (imgField == 'sh_ex36' || imgField == 'sh_ex37') {
                    // 拍照识按钮要显示不能设置maxCount=1，不然上传一张图就没了按钮
                    if (modelArr.value.length > 1) {
                        modelArr.value.shift();
                    }
                    emits('update:modelValue', res[0].url);
                    // 用过拍照识别后续上传身份证都要进行idOrc验证信息
                    if (isIdOrc) {
                        idOrcApi({
                            img: obj,
                        })
                            .then((res: any) => {
                                if (res.idcard_number_type == 1) {
                                    let obj = res.words_result;

                                    let myobj1 = JSON.parse(JSON.stringify(allFormData));
                                    if (imgField == 'sh_ex36') {
                                        myobj1.sh_ex1 = obj['姓名'].words;
                                        myobj1.sh_ex2 = obj['公民身份号码'].words;
                                    } else if (imgField == 'sh_ex37') {
                                        myobj1.sh_ex5 = obj['姓名'].words;
                                        myobj1.sh_ex35 = obj['公民身份号码'].words;
                                    }
                                    emits('update:allFormData', myobj1);
                                } else {
                                    throw new Error('身份证验证失败');
                                }
                                file.status = 'done';
                                file.message = '上传完成';
                            })
                            .catch((err) => {
                                console.log(err);
                                showFailToast('识别失败');
                                file.status = 'done';
                                file.message = '上传完成';
                            });
                    } else {
                        file.status = 'done';
                        file.message = '上传完成';
                    }
                } else {
                    if (modelValue) {
                        emits('update:modelValue', modelValue.concat(',', res[0].url));
                    } else {
                        emits('update:modelValue', modelValue.concat(res[0].url));
                    }
                    file.status = 'done';
                    file.message = '上传完成';
                }
            })
            .catch((err) => {
                file.status = 'failed';
                file.message = '上传失败';
                modelArr.value.pop();
                showFailToast('上传失败');
                console.log(err);
            });
    };
</script>

<style lang="scss" scoped>
    .uploader-box {
        border-bottom: 1px solid #999999;
        margin: 6px 15px;
        box-sizing: border-box;
        padding: 0px 0;
        height: 180px;
        overflow: hidden;
        img {
            width: 345px;
            height: 180px;
        }
        // 上传图片后图片大小
        :deep(.van-uploader__preview-image) {
            width: 345px;
            height: 180px;
        }
    }
</style>
